package cn.stylefeng.guns.modular.order.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.order.entity.OrderWeightBox;
import cn.stylefeng.guns.modular.order.mapper.OrderWeightBoxMapper;
import cn.stylefeng.guns.modular.order.model.params.OrderWeightBoxParam;
import cn.stylefeng.guns.modular.order.model.params.OrderWeightCheckParam;
import cn.stylefeng.guns.modular.order.model.result.OrderWeightBoxResult;
import  cn.stylefeng.guns.modular.order.service.OrderWeightBoxService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单包材重量 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-05-29
 */
@Service
public class OrderWeightBoxServiceImpl extends ServiceImpl<OrderWeightBoxMapper, OrderWeightBox> implements OrderWeightBoxService {

    @Override
    public void add(OrderWeightBoxParam param){
        OrderWeightBox entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(OrderWeightBoxParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(OrderWeightBoxParam param){
        OrderWeightBox oldEntity = getOldEntity(param);
        OrderWeightBox newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public OrderWeightBoxResult findBySpec(OrderWeightBoxParam param){
        return this.baseMapper.findByBoxCode(param.getBoxCode());
    }

    @Override
    public List<OrderWeightBoxResult> findListBySpec(OrderWeightBoxParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(OrderWeightBoxParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getExceldata(MultipartFile file, OrderWeightBoxParam orderWeightBoxParam, ResponseData data) throws Exception {
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        List<OrderWeightBoxParam> list = new ArrayList<OrderWeightBoxParam>();
        OrderWeightBoxParam __orderWeightBoxParam = null;
        for (int r = 1; r <= sheet.getLastRowNum() + 1; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //实体类
            __orderWeightBoxParam = new OrderWeightBoxParam();
            //交付客户
            __orderWeightBoxParam.setDeliverId(orderWeightBoxParam.getDeliverId());
            //部门
            __orderWeightBoxParam.setDeptId(orderWeightBoxParam.getDeptId());
            //创建时间
            __orderWeightBoxParam.setCreateTime(orderWeightBoxParam.getCreateTime());
            //创建人
            __orderWeightBoxParam.setCreateUser(orderWeightBoxParam.getCreateUser());
            //修改人
            __orderWeightBoxParam.setUpdateUser(orderWeightBoxParam.getUpdateUser());

            String boxCode = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(boxCode)) {
                __orderWeightBoxParam.setBoxCode(boxCode);
            }

            String weight = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(weight)) {
                __orderWeightBoxParam.setWeight(Long.valueOf(weight));
            }
            //
            this.baseMapper.delByBoxCode(boxCode);
            list.add(__orderWeightBoxParam);
        }
        //批量保存
        this.baseMapper.saveBatchList(list);

        data.setSuccess(true);
        return data;
    }

    private Serializable getKey(OrderWeightBoxParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private OrderWeightBox getOldEntity(OrderWeightBoxParam param) {
        return this.getById(getKey(param));
    }

    private OrderWeightBox getEntity(OrderWeightBoxParam param) {
        OrderWeightBox entity = new OrderWeightBox();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }
}
